# -*- coding: utf-8 -*-
"""
数据库字典信息提取器
"""
from typing import Dict, List, Optional
from database.mysql_connector import MySQLConnector

class DictExtractor:
    """数据库字典信息提取器"""
    
    def __init__(self, mysql_connector: MySQLConnector):
        self.mysql_connector = mysql_connector
    
    def extract_database_dict(self, selected_tables: Optional[List[str]] = None) -> Dict:
        """
        提取数据库字典信息
        
        Args:
            selected_tables: 选择的表名列表，None表示提取所有表
            
        Returns:
            数据库字典信息
        """
        if not self.mysql_connector.is_connected():
            return {}
        
        try:
            # 获取数据库信息
            db_info = self.mysql_connector.get_database_info()
            
            # 获取所有表名
            all_tables = self.mysql_connector.get_tables()
            
            # 确定要处理的表
            if selected_tables is None:
                tables_to_process = all_tables
            else:
                tables_to_process = [table for table in selected_tables if table in all_tables]
            
            # 提取表结构信息
            tables_info = []
            for table_name in tables_to_process:
                table_info = self.mysql_connector.get_table_structure(table_name)
                if table_info:
                    tables_info.append(table_info)
            
            result = {
                'database_info': db_info,
                'tables': tables_info,
                'total_tables': len(tables_to_process),
                'processed_tables': len(tables_info)
            }
            
            # 调试信息（生产环境可注释掉）
            # print(f"提取数据库字典信息: 选择表数={len(selected_tables) if selected_tables else 0}, 处理表数={len(tables_to_process)}, 成功表数={len(tables_info)}")
            return result
            
        except Exception as e:
            print(f"提取数据库字典信息失败: {e}")
            return {}
    
    def get_table_preview(self, table_name: str) -> Dict:
        """
        获取表结构预览
        
        Args:
            table_name: 表名
            
        Returns:
            表结构预览信息
        """
        if not self.mysql_connector.is_connected():
            return {}
        
        try:
            table_info = self.mysql_connector.get_table_structure(table_name)
            if not table_info:
                return {}
            
            # 格式化预览信息
            preview = {
                'table_name': table_info['name'],
                'table_comment': table_info['comment'],
                'column_count': len(table_info['columns']),
                'index_count': len(table_info['indexes']),
                'columns_preview': [],
                'indexes_preview': []
            }
            
            # 字段预览（显示所有字段）
            for column in table_info['columns']:
                preview['columns_preview'].append({
                    'name': column['name'],
                    'type': column['type_display'],
                    'nullable': column['nullable'],
                    'key': column['key'],
                    'default': column.get('default', ''),
                    'comment': column['comment']
                })
            
            # 索引预览
            for index in table_info['indexes']:
                preview['indexes_preview'].append({
                    'name': index['name'],
                    'type': index['type'],
                    'unique': index['unique'],
                    'columns': ', '.join(index['columns'])
                })
            
            return preview
            
        except Exception as e:
            print(f"获取表预览失败: {e}")
            return {}
    
    def validate_tables(self, table_names: List[str]) -> Dict[str, bool]:
        """
        验证表名是否有效
        
        Args:
            table_names: 表名列表
            
        Returns:
            表名验证结果字典
        """
        if not self.mysql_connector.is_connected():
            return {table: False for table in table_names}
        
        try:
            existing_tables = set(self.mysql_connector.get_tables())
            return {table: table in existing_tables for table in table_names}
            
        except Exception as e:
            print(f"验证表名失败: {e}")
            return {table: False for table in table_names}
    
    def get_database_statistics(self) -> Dict:
        """
        获取数据库统计信息
        
        Returns:
            数据库统计信息
        """
        if not self.mysql_connector.is_connected():
            return {}
        
        try:
            cursor = self.mysql_connector.connection.cursor()
            
            # 获取表数量
            cursor.execute("SELECT COUNT(*) FROM information_schema.TABLES WHERE TABLE_SCHEMA = DATABASE()")
            table_count = cursor.fetchone()[0]
            
            # 获取总字段数量
            cursor.execute("""
                SELECT COUNT(*) 
                FROM information_schema.COLUMNS 
                WHERE TABLE_SCHEMA = DATABASE()
            """)
            column_count = cursor.fetchone()[0]
            
            # 获取总索引数量
            cursor.execute("""
                SELECT COUNT(DISTINCT INDEX_NAME) 
                FROM information_schema.STATISTICS 
                WHERE TABLE_SCHEMA = DATABASE()
            """)
            index_count = cursor.fetchone()[0]
            
            # 获取数据库大小
            cursor.execute("""
                SELECT 
                    ROUND(SUM(data_length + index_length) / 1024 / 1024, 2) AS 'DB Size in MB'
                FROM information_schema.tables 
                WHERE table_schema = DATABASE()
            """)
            db_size = cursor.fetchone()[0] or 0
            
            cursor.close()
            
            return {
                'table_count': table_count,
                'column_count': column_count,
                'index_count': index_count,
                'database_size_mb': db_size
            }
            
        except Exception as e:
            print(f"获取数据库统计信息失败: {e}")
            return {}
    
    def get_table_dependencies(self, table_name: str) -> Dict:
        """
        获取表的外键依赖关系
        
        Args:
            table_name: 表名
            
        Returns:
            表依赖关系信息
        """
        if not self.mysql_connector.is_connected():
            return {}
        
        try:
            cursor = self.mysql_connector.connection.cursor()
            
            # 获取外键信息
            cursor.execute("""
                SELECT 
                    CONSTRAINT_NAME,
                    COLUMN_NAME,
                    REFERENCED_TABLE_NAME,
                    REFERENCED_COLUMN_NAME
                FROM information_schema.KEY_COLUMN_USAGE 
                WHERE TABLE_SCHEMA = DATABASE() 
                AND TABLE_NAME = %s
                AND REFERENCED_TABLE_NAME IS NOT NULL
            """, (table_name,))
            
            foreign_keys = []
            for row in cursor.fetchall():
                foreign_keys.append({
                    'constraint_name': row[0],
                    'column_name': row[1],
                    'referenced_table': row[2],
                    'referenced_column': row[3]
                })
            
            # 获取被其他表引用的信息
            cursor.execute("""
                SELECT 
                    TABLE_NAME,
                    COLUMN_NAME,
                    CONSTRAINT_NAME
                FROM information_schema.KEY_COLUMN_USAGE 
                WHERE TABLE_SCHEMA = DATABASE() 
                AND REFERENCED_TABLE_NAME = %s
            """, (table_name,))
            
            referenced_by = []
            for row in cursor.fetchall():
                referenced_by.append({
                    'table_name': row[0],
                    'column_name': row[1],
                    'constraint_name': row[2]
                })
            
            cursor.close()
            
            return {
                'foreign_keys': foreign_keys,
                'referenced_by': referenced_by
            }
            
        except Exception as e:
            print(f"获取表依赖关系失败: {e}")
            return {}
